<template>
	<div class="translation" curPageName="sfsadf23424534525234322">
		<searchBar close-plan="true" ref="searchbar" placeholder="用户名" close-advanced close-enter
			:search_val="search_val" @search-event="searchBarPost" v-model="searchform">
			<!-- 高级搜索弹出框 插槽-->
			<template #searchForm="searchProp">
				<!--  高级搜索弹出框内容-->
				<div class="modal-content">
					<!-- 高级搜索 -->
					<div class="modal-title"></div>
		
					<div class="modal—body">
						<el-scrollbar class="search_from_scrollbar" height="100%">
							<div class="scrollbar-content">
								<!-- 已选参数 组件-->
								<div class="r89768"></div>
								<!-- 表单 -->
								<el-form :model="searchform" :rules="searchformRules" label-position="top"
									ref="searchFormRef">
									<el-row :gutter="40">
										<el-col :span="8">
											<el-form-item :label="$t('manage_record.employee_name')"
												prop="employee_name.value">
												<el-input class="qf_input"
													v-model="searchform.employee_name.value" />
											</el-form-item>
										</el-col>
										<el-col :span="8">
											<el-form-item :label="$t('manage_record.job_number')">
												<el-input class="qf_input"
													v-model="searchform.job_number.value" />
											</el-form-item>
										</el-col>
										<el-col :span="8">
											<el-form-item :label="$t('manage_record.rangetime')">
												<el-date-picker v-model="rangeTime" type="daterange"
													:start-placeholder="$t('leaves_record_list.begin')"
													:end-placeholder="$t('leaves_record_list.end')"
													class="qf_date" @change="dataPost" :format="format"
													value-format="YYYY-MM-DD" />
											</el-form-item>
										</el-col>
										<el-col :span="8">
											<el-form-item :label="$t('manage_record.type')">
												<el-select class="qf_select" v-model="searchform.type.value"
													:placeholder="$t('merak.placeholder_select')">
													<el-option v-for="item in searchform.type.options"
														:key="item.value" :label="item.label"
														:value="item.value" />
												</el-select>
											</el-form-item>
										</el-col>
									</el-row>
								</el-form>
								<!-- 表单 -->
							</div>
						</el-scrollbar>
					</div>
					<div class="modal-footer">
						<!-- 取消 -->
						<el-button type="default"
							@click="closeModal(searchFormRef)">{{ $t("merak.reset") }}</el-button>
						<!-- 搜索 -->
						<el-button type="primary"
							@click="submitForm(searchFormRef)">{{ $t("merak.search") }}</el-button>
						<!-- 保存搜索方案 -->
						<el-button plain type="primary" v-if="searchProp.closePlan" @click="showPlanModal">
							{{ $t("merak.save_search_scheme") }}
						</el-button>
					</div>
				</div>
				<!--  高级搜索弹出框内容-->
			</template>
			<!-- /高级搜索弹出框 插槽-->
			<template #header>
				<div class="search_header_slot">
					<!-- <el-select v-model="selectedValue" remote :filter-method="filterMethod"
						@change="fliterChange" filterable clearable :placeholder="$t('sys_log.user_name')"
						style="width: 180px">
						<el-option v-for="item in filterResultOption" :key="item.value" :label="item.label"
							:value="item.value" />
					</el-select> -->
					<!-- <el-date-picker v-model="rangeTime" type="daterange" :start-placeholder="msg.beginDate"
						:end-placeholder="msg.endDate" @change="dataPost" :format="format"
						value-format="YYYY-MM-DD" class="sys_log_date" /> -->
				</div>
			</template>
		</searchBar>
		<div class="merak-table-wrapper">
			<MerakXTable ref="tableRef" :showHeader="false" :columns-by-store="JSON.parse(JSON.stringify(state.columns))"
				:query-columns="handleQueryColumns" :query-data="handleQueryData" :params="state.params"
				:column-type="columnTypeAuth" :batches="[]" :batch-click="handleBatchClick">
				<template #handler="{ row }">
					<div>
						<!-- // 权限04 -->
						<el-button type="primary" link @click="drawerShow(row)"> {{ $t("sys_log.view") }}
						</el-button>
					</div>
				</template>
		
				<template #actionslots="{ row }">
					<el-tag v-if="row.type == 'insert'" type="success">新增</el-tag>
					<el-tag v-if="row.type == 'update'" type="info">编辑</el-tag>
		
					<el-tag v-if="row.type == 'delete'" type="danger">删除</el-tag>
				</template>
			</MerakXTable>
		</div>

		<el-drawer modal-class="merak_modal manage_drawer" v-model="drawerSysDetail" direction="rtl" size="50%">
			<template #header>
				<div class="merak_modal_title">{{ $t("sys_log.logDetail") }}</div>
			</template>
			<div class="merak_modal_content">
				<div v-loading="loadDataStatus"></div>
				<div class="base_info">
					<ul>
						<li class="operator">{{ $t("sys_log.operator") }}: {{ recordDetail?.userInfo?.name }}</li>
						<li class="job_id">{{ $t("sys_log.jobId") }}: {{ recordDetail?.userInfo?.jobId }}</li>
						<li class="operation_method">{{ $t("sys_log.operationMethod") }}:
							{{ recordDetail?.userInfo?.operation }}</li>
						<!-- <li class="operation_method">操作时间：{{ recordDetail?.userInfo?.time }}</li> -->
						<li class="web_url">{{ $t("sys_log.pagePath") }}: {{ recordDetail?.userInfo?.webUrl }}</li>
					</ul>
				</div>
				<div class="record_base_info"></div>
				<el-divider />
				<div class="record">
					<el-scrollbar height="100%" always>
						<el-timeline class="timeline" style="max-width: 800px">
							<el-timeline-item v-for="(item, index) in recordDetail.records" :key="index"
								:timestamp="item?.operationTime">
								<template #dot>
									<div v-if="item.action == 'insert'" class="action-icon action-icon-plus">
										<el-icon size="11">
											<Plus />
										</el-icon>
									</div>

									<div v-if="item.action == 'delete'" class="action-icon action-icon-delete">
										<el-icon size="11">
											<Close />
										</el-icon>
									</div>

									<div v-if="item.action == 'update'" class="action-icon action-icon-update">
										<el-icon size="11">
											<Refresh />
										</el-icon>
									</div>
								</template>
								{{ preProcessData(item) }}
								<!-- <template v-html="preProcessData(item)">

               </template> -->
							</el-timeline-item>
						</el-timeline>
					</el-scrollbar>
				</div>
			</div>
		</el-drawer>
	</div>
</template>

<script lang="ts" setup name="logSRecord">
	import router from "@/routers";
	import { useRoute } from "vue-router";
	import { Plus, Edit, Delete, EditPen } from "@element-plus/icons-vue";

	import { ref, reactive, onMounted, getCurrentInstance, registerRuntimeCompiler } from "vue";
	import { useSysLogInit, useDrawerSysDetail, useLoading, useGetRecordFn } from "./index.ts";
	import { ResultEnum } from "@/enums/httpEnum";
	import searchBar from "@/components/SearchBar";
	import merakColapse from "@/components/merakColapse/index.vue";
	import selectedParams from "@/components/SearchBar/components/selectedParams.vue";

	import MerakXTable, { MerakXTableInstance, MerakXTableColumn, MerakXTableQuery } from "@/components/MerakXTable";
	import {
		moreConfirm,
		confirmWarningMsg,
		successMsg,
		warnMsg,
		failMsg,
		confirmSuccessMsg,
		delConfimMsg
	} from "@/utils/messageUtils";
	//import { getSysLogHeader, getSysLogList, saveCreateSet, saveEditSet, delSet } from "@/api/modules/personalManagementApi/holiday";
	import {
		getTableHeader, getTableData
	} from "@/api/modules/goodsArchive/list/detail";
	import I18n from "@/languages/index";

	import type { ElForm } from "element-plus";
	import { pa } from "element-plus/es/locale";
	const route = useRoute();
	type FormInstance = InstanceType<typeof ElForm>;
	const setRef = ref<FormInstance>();
	const logType = ref("");

	const productId = ref("");
	const typeId = ref("");

	const { proxy } = getCurrentInstance();
	const msg = reactive({
		beginDate: proxy.$t("sys_log.beginDate"),
		endDate: proxy.$t("sys_log.endDate")
	});
	const showRemainingData = [
		{
			update_at: "sfsadfasd",
			days: "sdfsd",
			action: "sfgggg"
		}
	];

	const tableRef = ref<MerakXTableInstance>();

	const color = ref("rgba(255, 69, 0, 0.68)");
	const predefineColors = ref(["#E63415", "#FF6600", "#FFDE0A", "#1EC79D", "#14CCCC", "#4167F0", "#6222C9"]);

	//批量操作
	const handleBatchClick = async e => {
		console.log(e);
	};

	//#region 搜索表单
	let search_val = ref("");
	//触发了快速搜索或者搜索方案
	const searchFn = params => {
		console.log(params);
		let postParams = { ...params.params, search: params.search };
		state.params = postParams;
	};

	//#endregion

	//#region  同步翻译 publishJs
	const simultaneousTrans = () => {
		publishJs().then(res => {
			if (res.code == ResultEnum.SUCCESS) {
				successMsg("同步成功!请重新加载。");
			}
		});
	};

	//#endregion

	//#region 新增、编辑、删除
	// const drawerTranslation = ref(false);
	const translationTitle = ref("新增假期");
	//表单参数结构
	const setForm = ref({
		user_leaves_set_id: 0,
		title: "",
		title_ru: "",
		remarks: "",
		remarks_ru: "",
		days: "",
		color: "#E63415"
	});
	const validateDay = (rule : any, value : any, callback : any) => {
		if (value === "") {
			callback(new Error(proxy.$t("main.requiredMsg")));
		} else {
			let reg = /^-?(0|([1-9][0-9]*))(\.[\d]+)?$/;
			if (reg.test(value)) {
			} else {
				callback(new Error("必须数字"));
			}
			callback();
		}
	};
	const translationRules = reactive({
		title: [{ required: true, message: proxy.$t("main.requiredMsg"), trigger: "change" }],
		title_ru: [{ required: true, message: proxy.$t("main.requiredMsg"), trigger: "change" }],
		remarks: [{ required: true, message: proxy.$t("main.requiredMsg"), trigger: "change" }],
		remarks_ru: [{ required: true, message: proxy.$t("main.requiredMsg"), trigger: "change" }],
		days: [{ required: true, validator: validateDay, trigger: "change" }]
	});

	const resetForm = (formEl : FormInstance | undefined) => {
		if (!formEl) return;
		formEl.resetFields();
	};
	//新增操作
	const onPlus = () => {
		setForm.value = {
			user_leaves_set_id: 0,
			title: "",
			title_ru: "",
			remarks: "",
			remarks_ru: "",
			days: "",
			color: "#E63415"
		};

		resetForm(setRef.value);
		//打开弹窗
		// drawerTranslation.value = true;
	};

	//新增
	/**
	 * typebtn 1保存 2保存并继续
	 */
	const postAdd = (typebtn : string, formEl : FormInstance | undefined) => {
		if (editShow.value) {
			//新增
			saveCreateSet(setForm.value).then(
				res => {
					console.log(res);
					if (res.code == ResultEnum.SUCCESS) {
						successMsg("保存成功!");
						if (typebtn == 1) {
							//关闭弹窗
							// drawerTranslation.value = false;
							//formEl.resetFields();
						} else {
							let resetObj = {
								user_leaves_set_id: 0,
								title: "",
								title_ru: "",
								remarks: "",
								remarks_ru: "",
								days: "",
								color: "#E63415"
							};
							setForm.value = { ...setForm.value, ...resetObj };

							resetForm(setRef.value);
						}

						tableRef.value?.reloadData();
					} else {
						failMsg(res.message);
					}
				},
				err => {
					console.log(err);
				}
			);
		} else {
			//编辑
			saveEditSet(setForm.value).then(
				res => {
					if (res.code == ResultEnum.SUCCESS) {
						successMsg("编辑成功!");
						//关闭弹窗
						// drawerTranslation.value = false;
						// formEl.resetFields();
						tableRef.value?.reloadData();
					} else {
						failMsg(res.message);
					}
				},
				err => {
					console.log(err);
				}
			);
		}
	};

	//编辑
	let editShow = ref(true);
	const saveEdit = (row : setForm) => {
		const rowt = JSON.parse(JSON.stringify(row));
		setForm.value = rowt;
		//打开弹窗
		// drawerTranslation.value = true;
		editShow.value = false;
	};

	//取消
	const cancelEmpty = (formEl : FormInstance | undefined) => {
		if (!formEl) return;
		formEl.resetFields();
		// drawerTranslation.value = false;
	};

	//删除
	const delTranslation = (row : setForm) => {
		delConfimMsg({
			callback: val => {
				if (val == "confirm") {
					delOne(row);
				}
			}
		});
	};

	const delOne = (row : setForm) => {
		delSet({ user_leaves_set_id: row.user_leaves_set_id }).then(res => {
			successMsg("删除成功!");
			setTimeout(() => {
				tableRef.value?.reloadData();
			}, 500);
		});
	};
	//#endregion

	const state = reactive<{
		params : Record<string, any>;
		columns : MerakXTableColumn[];
	}>({
		params: {
			key_words: ""
		},
		columns: []
	});

	//权限01数据
	let authArr = ref({});

	const $t = I18n.global.t;

	const columnTypeAuth = reactive([]);

	if ($t("lang") == "ru") {
		Object.assign(columnTypeAuth, [{ type: "handle", width: 280, slot: "handler" }]);
	} else {
		Object.assign(columnTypeAuth, [{ type: "handle", width: 120, slot: "handler" }]);
	}

	//列表内容展示区
	const handleQueryData : MerakXTableInstance["queryData"] = async ({ page, sorts, filters, from }) => {
		const params : Record<string, any> = {};
		params.product_id = route.query.p_id;
		params.type_id = route.query.t_id;


		if (!!page) {
			Object.assign(params, { ...page }, from);
		}
		// await getRouterParams(router).then(res => {
		//    let path = res.currentRoute.value.path;
		//    logType.value = path.split("/")[2];
		//    Object.assign(params, { logType: logType.value });
		//  }); 
		return await getTableData(params).then(res => {
			if (res.code == ResultEnum.SUCCESS) {
				let data = res.data;

				for (let index = 0; index < data.table_data.list.length; index++) {
					const element = data.table_data.list[index];
					if (element.type == "insert" || element.type == "delete") {
						var newShow = [];

						for (const key in element.new) {
							var newObj = {};
							newObj["label"] = key;
							newObj["value"] = element.new[key];
							newShow.push(newObj);
						}

						element["tablexqShow"] = newShow;
					}
				}

				console.log(data.table_data);

				const { table_data, language } = data as { table_data : Record<string, any>; language : Record<string, any> };

				return table_data;
			}
		});
	};

	//表头信息
	const handleQueryColumns : MerakXTableInstance["queryColumns"] = async () => {
		return await getTableHeader().then(res => {
			if (res.code == ResultEnum.SUCCESS) {
				let data = res.data as MerakXTableQuery.Columns;
				// const { pageSize, columns } = data as { pageSize: number; columns: MerakXTableColumn[] };
				console.log(data.columns);

				for (let index = 0; index < data.columns.length; index++) {
					const element = data.columns[index];
					if (element.field == "type") {
						element["slots"] = { default: `actionslots` };
					}
				}

				state.columns = data.columns;

				return data;
			}
		});
	};

	// 获取高级搜索方案
	const queryFilterOptions = async data => {
		searchbar.value.getPlanList(data.table_id);
		// 初始化接口需要传入队列 loading 暴露的 id
	};

	const dataPost = params => {
		if (!rangeTime.value) {
			rangeTime.value = ["", ""];
		}
		searchform.rangeTime.value = "(" + rangeTime.value[0] + ")-" + "(" + rangeTime.value[1] + ")";
		let postParams = { begin_date: rangeTime.value[0], end_date: rangeTime.value[1], ...params, ...{ logType: logType.value } };

		state.params = postParams;
	};
	const rangeTime = ref(["", ""]);
	// 高级搜索
	// 高级搜索表单
	const searchFormRef = ref<FormInstance>();
	const searchform = reactive({
		employee_name: {
			label: "姓名",
			value: ""
		},
		job_number: {
			label: "工号",
			value: ""
		},
		rangeTime: {
			label: "时间",
			value: ""
		},
		type: {
			label: "请假类型",
			value: "",
			text: "rewiqruhewqio",
			type: "select",
			options: []
		}
	});

	// 高级搜索表单验证
	const searchformRules = reactive({});

	//高级搜索模态
	const searchbar = ref();

	//触发了快速搜索或者搜索方案
	const searchBarPost = params => {
		console.log(params);
		searchform.employee_name.value = "";
		searchform.job_number.value = "";
		rangeTime.value = [];
		searchform.type.value = "";

		let postParams = { ...params.params, search: params.search };
		state.params = postParams;
	};

	//点击取消按钮关闭高级搜索模态框
	const closeModal = (formEl : FormInstance | undefined) => {
		searchFormRef.value?.resetFields();
		searchbar.value.modalHide();
		searchbar.value.clear();

		searchform.employee_name.value = "";
		searchform.job_number.value = "";
		rangeTime.value = ["", ""];
		searchform.type.value = "";

		state.params = {};
	};

	//打开搜索方案弹出
	const showPlanModal = () => {
		searchbar.value.showPlanModal();
		companyLink();
	};

	//搜索表单提交
	const submitForm = async (formEl : FormInstance | undefined) => {
		search_val.value = "";
		let postParams = {
			begin_date: rangeTime.value[0],
			end_date: rangeTime.value[1],
			employee_name: searchform.employee_name.value,
			job_number: searchform.job_number.value,
			type: searchform.type.value
		};
		state.params = postParams;

		searchbar.value.clear();
		searchbar.value.modalHide();
	};

	// 日志记录--start

	const { recordDetail, getRecord, getUserList, getRouterParams } = useSysLogInit();
	const { loadDataStatus, setLoadingShow, setLoadingHide } = useLoading();
	const { drawerSysDetail, drawerSetShow } = useDrawerSysDetail();
	const { recordLangFn } = useGetRecordFn(proxy);

	//获取url

	//获取用户信息

	const { userListOptions, refreshUserList, filterResultOption, selectedValue, filterMethod } = getUserList();

	//按人名过滤回调
	const fliterChange = () => {
		dataPost({ user_id: selectedValue });
	};

	//显示抽屉
	const drawerShow = row => {
		drawerSetShow(row, getRecordFn);
	};

	//获取日志数据
	const getRecordFn = (params) : void => {
		setLoadingShow();
		getRecord(params).then(res => {
			if (res.code == ResultEnum.SUCCESS) {
				setLoadingHide();
				recordDetail.userInfo = res.data.userInfo;
				recordDetail.records = res.data.records;
			}
		});
	};

	// 预处理数据，
	const preProcessData = data => {
		let langCategory = data.tableName || "table1";
		let action = data.action;
		let isChild = "name" in data ? true : false;
		return recordLangFn[action](data, isChild);
	};
	// 日志记录--end
	onMounted(() => {
		//refreshUserList();
		productId.value = route.query.p_id;
		typeId.value = route.query.t_id;
	});
</script>

<style lang="scss" scoped>
	@import url("./index.scss");
</style>